package com.nowcoder.community.controller;/**
 * 功能描述
 *
 * @author 21775
 * @date 2022/09/14  10:53
 */

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityConstUtil;
import com.nowcoder.community.utils.MailClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.*;

/**
 *@ClassName HomeController
 *@Description TODO 家控制类
 *@Author 21775
 *@Date 2022/9/14 10:53
 *@Version 1.0
 */
@Slf4j
@Controller
public class HomeController {
    @Resource
    private UserService userService;

    @Resource
    private DiscussPostService discussPostService;

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private MailClient mailClient;

    @Resource
    private LikeService likeService;

    @GetMapping("/index")
    public String index(Model model,Page page,@RequestParam(name = "orderMode",defaultValue = "0") int orderMode){
        log.info(page.toString());
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/index?orderMode="+orderMode);
        List<DiscussPost> discussPostList=discussPostService.selectDiscussPost(0,page.getOffset(),page.getLimit(),orderMode);
        ArrayList<Map<String,Object>> result=new ArrayList<>();
        for(DiscussPost discussPost:discussPostList){
            Map<String,Object> map=new HashMap<>();
            map.put("post",discussPost);
            map.put("user",userService.findUserById(discussPost.getUserId()));
            long likeCount=likeService.findEntityLikeCount(CommunityConstUtil.ENTITY_TYPE_POST,discussPost.getId());
            map.put("likeCount",likeCount);
            result.add(map);
        }
        model.addAttribute("discussPosts",result);
        model.addAttribute("orderMode",orderMode);
        return "/index";
    }

    @GetMapping("/test")
    public String test(){
        Context context = new Context();
        context.setVariable("username", "lvming");

        String content = templateEngine.process("/mail/demo", context);
        System.out.println(content);

        mailClient.sendMail("2177502081@qq.com", "HTML", content);
        return "/mail/demo";
    }

    @GetMapping("/error")
    public String getErrorPage(){
        return "/error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }
}
